package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;

import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author whr
 * @version 1.0
 * @description: 课程分类信息管理接口
 * @date 2024/2/29 20:36
 */
@SuppressWarnings({"all"})
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //查询到所有课程分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos =courseCategoryMapper.selectTreeNodes(id);
        //最终返回结果
        List<CourseCategoryTreeDto> categoryTreeDtos = new ArrayList<>();
        //创建map，key为id，value为课程分类对象
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //遍历全部元素
        courseCategoryTreeDtos.stream().forEach(item -> {
            if (item.getParentid().equals(id)) {
                categoryTreeDtos.add(item);
            }
            CourseCategoryTreeDto parentTreeDto = mapTemp.get(item.getParentid());
            if (parentTreeDto != null) {
                if (parentTreeDto.getChildrenTreeNodes() == null) {
                    parentTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                parentTreeDto.getChildrenTreeNodes().add(item);
            }

        });

        return categoryTreeDtos;
    }
}
